<template>
  <el-drawer
    title="生成清单XML"
    :visible.sync="visible"
    direction="rtl"
    size="60%"
    :before-close="handleClose"
    :wrapper-closable="false"
    custom-class="manifest-xml-drawer"
  >
    <div class="drawer-container">
      <div class="drawer-content">
        <el-form :model="form" :rules="rules" ref="form" size="small">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="GUID(guid)" prop="guid">
                <el-input v-model="form.guid" disabled>
                  <el-button slot="append" @click="generateGuid">重新生成</el-button>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申报类型(appType)" prop="appType">
                <el-select v-model="form.appType" placeholder="请选择申报类型">
                  <el-option label="新增" value="1" />
                  <el-option label="变更" value="2" />
                  <el-option label="删除" value="3" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="申报时间(appTime)" prop="appTime">
                <el-input v-model="form.appTime" disabled>
                  <el-button slot="append" @click="refreshAppTime">刷新</el-button>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="订单编号(orderNo)" prop="orderNo">
                <el-input v-model="form.orderNo" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="电商平台代码(ebpCode)" prop="ebpCode">
                <el-input v-model="form.ebpCode" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="电商平台名称(ebpName)" prop="ebpName">
                <el-input v-model="form.ebpName" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="电商企业代码(ebcCode)" prop="ebcCode">
                <el-input v-model="form.ebcCode" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="电商企业名称(ebcName)" prop="ebcName">
                <el-input v-model="form.ebcName" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="物流运单号(logisticsNo)" prop="logisticsNo">
                <el-input v-model="form.logisticsNo" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="物流企业代码(logisticsCode)" prop="logisticsCode">
                <el-input v-model="form.logisticsCode" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="物流企业名称(logisticsName)" prop="logisticsName">
                <el-input v-model="form.logisticsName" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="企业内部编号(copNo)" prop="copNo">
                <el-input v-model="form.copNo" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="担保企业编号(assureCode)" prop="assureCode">
                <el-input v-model="form.assureCode" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="账册编号(emsNo)" prop="emsNo">
                <el-input v-model="form.emsNo" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="进出口标志(ieFlag)" prop="ieFlag">
                <el-select v-model="form.ieFlag" placeholder="请选择进出口标志">
                  <el-option label="进口" value="I" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="申报日期(declTime)" prop="declTime">
                <el-input v-model="form.declTime" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="申报海关代码(customsCode)" prop="customsCode">
                <el-input v-model="form.customsCode" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="口岸海关代码(portCode)" prop="portCode">
                <el-input v-model="form.portCode" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="申报企业代码(agentCode)" prop="agentCode">
                <el-input v-model="form.agentCode" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="申报企业名称(agentName)" prop="agentName">
                <el-input v-model="form.agentName" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="区内企业代码(areaCode)" prop="areaCode">
                <el-input v-model="form.areaCode" :disabled="form.tradeMode !== '1210'" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="区内企业名称(areaName)" prop="areaName">
                <el-input v-model="form.areaName" :disabled="form.tradeMode !== '1210'" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">订购人信息</el-divider>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="订购人证件类型(buyerIdType)" prop="buyerIdType">
                <el-select v-model="form.buyerIdType" disabled>
                  <el-option label="身份证" value="1" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="订购人证件号码(buyerIdNumber)" prop="buyerIdNumber">
                <el-input v-model="form.buyerIdNumber" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="订购人姓名(buyerName)" prop="buyerName">
                <el-input v-model="form.buyerName" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="订购人电话(buyerTelephone)" prop="buyerTelephone">
                <el-input v-model="form.buyerTelephone" />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="收货地址(consigneeAddress)" prop="consigneeAddress">
                <el-input v-model="form.consigneeAddress" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">清单表头</el-divider>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="贸易方式(tradeMode)" prop="tradeMode">
                <el-select v-model="form.tradeMode" placeholder="请选择贸易方式">
                  <el-option label="直邮进口" value="9610" />
                  <el-option label="保税进口" value="1210" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="运输方式(trafMode)" prop="trafMode">
                <el-input v-model="form.trafMode" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="起运国（地区）(country)" prop="country">
                <el-input v-model="form.country" placeholder="请输入起运国" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="运费(freight)" prop="freight">
                <el-input v-model="form.freight"  />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="保费(insuredFee)" prop="insuredFee">
                <el-input v-model="form.insuredFee"  />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="币制(currency)" prop="currency">
                <el-input v-model="form.currency" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="件数(packNo)" prop="packNo">
                <el-input v-model="form.packNo" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="毛重（公斤）(grossWeight)" prop="grossWeight">
                <el-input v-model="form.grossWeight" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="净重（公斤）(netWeight)" prop="netWeight">
                <el-input v-model="form.netWeight" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">进口清单表体</el-divider>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="商品序号(gnum)" prop="gnum">
                <el-input v-model="form.gnum" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="账册备案料号(itemRecordNo)" prop="itemRecordNo">
                <el-input v-model="form.itemRecordNo" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="商品编码(gcode)" prop="gcode">
                <el-input v-model="form.gcode" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="商品名称(gname)" prop="gname">
                <el-input v-model="form.gname" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="商品规格型号(gmodel)" prop="gmodel">
                <el-input v-model="form.gmodel" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="原产国（地区）(originCountry)" prop="originCountry">
                <el-input v-model="form.originCountry" placeholder="请输入原产国" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="数量(qty)" prop="qty">
                <el-input v-model="form.qty"  />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="法定数量(qty1)" prop="qty1">
                <el-input v-model="form.qty1"  />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="计量单位(unit)" prop="unit">
                <el-input v-model="form.unit" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="法定计量单位(unit1)" prop="unit1">
                <el-input v-model="form.unit1" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="第二计量单位(unit2)" prop="unit2">
                <el-input v-model="form.unit2" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单价(price)" prop="price">
                <el-input v-model="form.price" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="总价(totalPrice)" prop="totalPrice">
                <el-input v-model="form.totalPrice"  />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="备注(note)" prop="note">
                <el-input v-model="form.note" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="企业商品货号(itemNo)条形码" prop="itemNo">
              <el-input v-model="form.itemNo" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="贸易国（地区）(tradeCountry)" prop="tradeCountry">
                <el-input v-model="form.tradeCountry" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="drawer-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="generateXml">生成XML</el-button>
      </div>
    </div>


    <!-- XML内容弹窗 -->
    <el-dialog
      title="生成的XML"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleDialogClose"
      append-to-body
    >
      <el-input
        type="textarea"
        v-model="xmlContent"
        :rows="20"
        readonly
      />
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="copyXml">复制XML</el-button>
        <el-button type="success" @click="downloadXml">下载XML</el-button>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </el-drawer>
</template>

<script>
export default {
  name: 'ManifestXmlDrawer',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    orderId: {
      type: [String, Number],
      default: ''
    },
    detailForm: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    const validateEmsNo = (rule, value, callback) => {
      if (this.form.tradeMode === '1210' && !value) {
        callback(new Error('保税进口时账册编号不能为空'))
      } else {
        callback()
      }
    }
    return {
      form: {
        guid: '',
        appType: '1',
        appTime: '',
        appStatus: '2',
        orderNo: '',
        ebpCode: '',
        ebpName: '',
        ebcCode: '3210660A0E',
        ebcName: '扬州数贸港跨境电子商务有限公司',
        logisticsNo: '',
        logisticsCode: '3120980105',
        logisticsName: '上海韵达货运有限公司',
        copNo: '',
        assureCode: '',
        emsNo: '',
        ieFlag: 'I',
        declTime: '',
        customsCode: '',
        portCode: '',
        ieDate: '',
        buyerIdType: '1',
        buyerIdNumber: '',
        buyerName: '',
        buyerTelephone: '',
        consigneeAddress: '',
        tradeMode: '1210',
        trafMode: '',
        country: '',
        freight: '',
        insuredFee: '',
        currency: '142',
        wrapType: '2',
        packNo: '',
        grossWeight: '',
        netWeight: '',
        note: '',
        areaCode: '',
        areaName: '',
        // 进口清单表体参数
        gnum: '1',
        gcode: '',
        gname: '',
        gmodel: '',
        itemRecordNo: '',
        itemName:'',
        originCountry: '',
        tradeCountry: '110',
        listCurrency: '142',
        qty: '',
        qty1: '',
        unit: '',
        unit1: '',
        unit2: '',
        price: '',
        totalPrice: '',
        // 基础报文传输信息
        copCode: '3210660A0E',
        copName: '扬州数贸港跨境电子商务有限公司',
        dxpMode: 'DXP',
        dxpId: 'DXPENT2024716238',
        agentCode: '',
        agentName: ''
      },
      rules: {
        // 基本信息验证规则
        orderNo: [
          { required: true, message: '订单编号不能为空', trigger: 'blur' }
        ],
        ebpCode: [
          { required: true, message: '电商平台代码不能为空', trigger: 'blur' }
        ],
        ebpName: [
          { required: true, message: '电商平台名称不能为空', trigger: 'blur' }
        ],
        // 物流信息验证规则
        logisticsNo: [
          { required: true, message: '物流运单编号不能为空', trigger: 'blur' }
        ],
        logisticsCode: [
          { required: true, message: '物流企业代码不能为空', trigger: 'blur' }
        ],
        logisticsName: [
          { required: true, message: '物流企业名称不能为空', trigger: 'blur' }
        ],
        // 担保企业编号验证规则
        assureCode: [
          { required: true, message: '担保企业编号不能为空', trigger: 'blur' }
        ],
        // 收货人信息验证规则
        buyerName: [
          { required: true, message: '订购人姓名不能为空', trigger: 'blur' }
        ],
        buyerTelephone: [
          { required: true, message: '订购人电话不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        buyerIdNumber: [
          { required: true, message: '订购人证件号码不能为空', trigger: 'blur' },
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码', trigger: 'blur' }
        ],
        consigneeAddress: [
          { required: true, message: '收货地址不能为空', trigger: 'blur' }
        ],
        // 商品信息验证规则
        itemName: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ],
        gmodel: [
          { required: true, message: '商品规格型号不能为空', trigger: 'blur' }
        ],
        unit: [
          { required: true, message: '计量单位不能为空', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '单价不能为空', trigger: 'blur' },
          { type: 'number', message: '单价必须为数字', trigger: 'blur', transform: value => Number(value) }
        ],
        totalPrice: [
          { required: true, message: '总价不能为空', trigger: 'blur' },
          { type: 'number', message: '总价必须为数字', trigger: 'blur', transform: value => Number(value) }
        ],
        customsCode: [
          { required: true, message: '申报海关代码不能为空', trigger: 'blur' }
        ],
        portCode: [
          { required: true, message: '口岸海关代码不能为空', trigger: 'blur' }
        ],
        agentCode: [
          { required: true, message: '申报企业代码不能为空', trigger: 'blur' }
        ],
        agentName: [
          { required: true, message: '申报企业名称不能为空', trigger: 'blur' }
        ],
        tradeMode: [
          { required: true, message: '请选择贸易方式', trigger: 'change' }
        ],
        trafMode: [
          { required: true, message: '运输方式不能为空', trigger: 'blur' }
        ],
        country: [
          { required: true, message: '起运国（地区）不能为空', trigger: 'blur' }
        ],
        originCountry: [
          { required: true, message: '原产国（地区）不能为空', trigger: 'blur' }
        ],
        currency: [
          { required: true, message: '币制不能为空', trigger: 'blur' }
        ],
        listCurrency: [
          { required: true, message: '币制不能为空', trigger: 'blur' }
        ],
        freight: [
          { required: true, message: '运费不能为空', trigger: 'blur' },
          { type: 'number', message: '运费必须为数字', trigger: 'blur', transform: value => Number(value) }
        ],
        insuredFee: [
          { required: true, message: '保费不能为空', trigger: 'blur' },
          { type: 'number', message: '保费必须为数字', trigger: 'blur', transform: value => Number(value) }
        ],
        packNo: [
          { required: true, message: '件数不能为空', trigger: 'blur' },
          { type: 'number', message: '件数必须为数字', trigger: 'blur', transform: value => Number(value) }
        ],
        grossWeight: [
          { required: true, message: '毛重不能为空', trigger: 'blur' },
          { type: 'number', message: '毛重必须为数字', trigger: 'blur', transform: value => Number(value) }
        ],
        netWeight: [
          { required: true, message: '净重不能为空', trigger: 'blur' },
          { type: 'number', message: '净重必须为数字', trigger: 'blur', transform: value => Number(value) }
        ],
        gcode: [
          { required: true, message: '商品编码不能为空', trigger: 'blur' }
        ],
        gname: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ],
        gmodel: [
          { required: true, message: '商品规格型号不能为空', trigger: 'blur' }
        ],
        qty: [
          { required: true, message: '数量不能为空', trigger: 'blur' },
          { type: 'number', message: '数量必须为数字', trigger: 'blur', transform: value => Number(value) }
        ],
        qty1: [
          { required: true, message: '法定数量不能为空', trigger: 'blur' },
          { type: 'number', message: '法定数量必须为数字', trigger: 'blur', transform: value => Number(value) }
        ],
        unit: [
          { required: true, message: '计量单位不能为空', trigger: 'blur' }
        ],
        unit1: [
          { required: true, message: '法定计量单位不能为空', trigger: 'blur' }
        ],
        unit2: [
          { required: true, message: '第二计量单位不能为空', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '单价不能为空', trigger: 'blur' },
          { type: 'number', message: '单价必须为数字', trigger: 'blur', transform: value => Number(value) }
        ],
        totalPrice: [
          { required: true, message: '总价不能为空', trigger: 'blur' },
          { type: 'number', message: '总价必须为数字', trigger: 'blur', transform: value => Number(value) }
        ],
        emsNo: [
          { validator: validateEmsNo, trigger: 'change' }
        ],
        itemRecordNo: [
          { required: true, message: '账册备案料号不能为空', trigger: 'blur' },
          { validator: (rule, value, callback) => {
            if (this.form.tradeMode === '1210' && !value) {
              callback(new Error('保税进口时账册备案料号不能为空'))
            } else {
              callback()
            }
          }, trigger: 'change' }
        ],
        tradeCountry: [
          { required: true, message: '贸易国（地区）不能为空', trigger: 'blur' }
        ],
        areaCode: [
          { validator: (rule, value, callback) => {
            if (this.form.tradeMode === '1210' && !value) {
              callback(new Error('保税进口时区内企业代码不能为空'))
            } else {
              callback()
            }
          }, trigger: 'change' }
        ],
        areaName: [
          { validator: (rule, value, callback) => {
            if (this.form.tradeMode === '1210' && !value) {
              callback(new Error('保税进口时区内企业名称不能为空'))
            } else {
              callback()
            }
          }, trigger: 'change' }
        ]
      },
      xmlContent: '',
      dialogVisible: false
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.form.orderNo = this.orderId
        this.generateGuid()
        this.refreshAppTime()
        this.form.declTime = this.form.appTime.substring(0, 8)
        this.form.ieDate = this.form.appTime.substring(0, 8)

        // 填充基本信息
        if (this.detailForm) {
          // 电商平台信息
          this.form.ebpCode = this.detailForm.ebpCode || ''
          this.form.ebpName = this.detailForm.ebpName || ''

          // 物流信息 - 只设置运单号，其他需要用户手动填写
          this.form.logisticsNo = this.detailForm.logistics_no || ''

          // 订购人信息和收货地址
          this.form.buyerIdNumber = this.detailForm.ConsigneeCode1 || ''  // 订购人证件号码
          this.form.buyerName = this.detailForm.buyerName || ''         // 订购人姓名
          this.form.buyerTelephone = this.detailForm.contactMobile || ''

          //件数
          this.form.packNo = 1

          //企业内部编号
          this.form.copNo = 'D' + this.detailForm.id

          // 收货地址拼接
          this.form.consigneeAddress = [
            this.detailForm.contactAddr || '',
            this.detailForm.detailAddr || ''
          ].filter(Boolean).join('')

          // 商品表体信息
          if (this.detailForm.order_goods && this.detailForm.order_goods[0]) {
            const goods = this.detailForm.order_goods[0]
            // 保留两位小数
            this.form.price = Number(goods.goods_price || 0).toFixed(2)
            this.form.qty = goods.goods_num || 1
            this.form.totalPrice = Number(goods.goods_amount || 0).toFixed(2)
            this.form.gname = goods.goods_name || ''

            //跨境 海关香港字段
            this.form.itemRecordNo = goods.hg_itemRecordNo || ''
            this.form.gcode = goods.hg_gcode || ''
            this.form.gmodel = goods.hg_gmodel || ''
            this.form.originCountry = goods.hg_originCountry || ''
            this.form.qty1 = goods.hg_qty1 || ''
            this.form.unit = goods.hg_unit || ''
            this.form.unit1 = goods.hg_unit1 || ''
            this.form.unit2 = goods.hg_unit2 || ''

            console.log(goods.manifest_template)

            // 重量信息 
            // 净重 法定数量*数量 保留5位小数
            let numberQty1 = Number(this.form.qty1)
            this.form.netWeight = ( numberQty1 * this.form.qty).toFixed(5)
            // 毛重 (法定数量 + 0.2) *数量 保留5位小数
            this.form.grossWeight = ((numberQty1 + 0.2) * this.form.qty).toFixed(5)
            //重新修改法定数量，改成 法定数量 * 数量
            this.form.qty1 = (numberQty1 * this.form.qty).toFixed(5)

            //根据海关清单模版填充
            if(goods.manifest_template){
                //定义一个要修改的字段数组
                const fields = ['assureCode', 'emsNo', 'portCode','customsCode',
                    'areaCode','areaName','trafMode','country','insuredFee','agentCode','agentName'
                ];
                fields.forEach(field => {
                    this.form[field] = goods.manifest_template[field] || ''
                });
            }
          }

          // 海关编码等
          if (this.detailForm.order_goods && this.detailForm.order_goods[0]) {
            const goods = this.detailForm.order_goods[0]
            this.form.itemNo = goods._goods_detail?.barcode || ''
          }

          // 重置国家和币制字段
          this.form.currency = '142'  // 设置默认币制
          this.form.listCurrency = '142'  // 设置默认币制
          this.form.freight = 0
        }
      } else {
        // 关闭时重置表单
        this.$refs.form && this.$refs.form.resetFields()
      }
    }
  },
  methods: {
    generateGuid() {
      const hexDigits = '0123456789abcdef'
      const segments = [8, 4, 4, 4, 12]
      const guid = segments.map(len => {
        let segment = ''
        for (let i = 0; i < len; i++) {
          segment += hexDigits.charAt(Math.floor(Math.random() * 16))
        }
        return segment
      }).join('-')
      this.form.guid = guid.toUpperCase()
    },
    refreshAppTime() {
      const now = new Date()
      this.form.appTime =
        now.getFullYear() +
        String(now.getMonth() + 1).padStart(2, '0') +
        String(now.getDate()).padStart(2, '0') +
        String(now.getHours()).padStart(2, '0') +
        String(now.getMinutes()).padStart(2, '0') +
        String(now.getSeconds()).padStart(2, '0')
    },
    handleClose() {
      this.$emit('update:visible', false)
      this.$refs.form && this.$refs.form.resetFields()
    },
    handleDialogClose(done) {
      done()
    },
    generateXml() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 处理价格，确保XML中的价格保留两位小数
          const price = Number(this.form.price).toFixed(2)
          const totalPrice = Number(this.form.totalPrice).toFixed(2)

          this.refreshAppTime()
          this.xmlContent = `<?xml version="1.0" encoding="UTF-8"?>
<ceb:CEB621Message xmlns:ceb="http://www.chinaport.gov.cn/ceb" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" guid="${this.form.guid}" version="1.0">
  <ceb:Inventory>
    <ceb:InventoryHead>
      <ceb:guid>${this.form.guid}</ceb:guid>
      <ceb:appType>${this.form.appType}</ceb:appType>
      <ceb:appTime>${this.form.appTime}</ceb:appTime>
      <ceb:appStatus>${this.form.appStatus}</ceb:appStatus>
      <ceb:orderNo>${this.form.orderNo}</ceb:orderNo>
      <ceb:ebpCode>${this.form.ebpCode}</ceb:ebpCode>
      <ceb:ebpName>${this.form.ebpName}</ceb:ebpName>
      <ceb:ebcCode>${this.form.ebcCode}</ceb:ebcCode>
      <ceb:ebcName>${this.form.ebcName}</ceb:ebcName>
      <ceb:logisticsNo>${this.form.logisticsNo}</ceb:logisticsNo>
      <ceb:logisticsCode>${this.form.logisticsCode}</ceb:logisticsCode>
      <ceb:logisticsName>${this.form.logisticsName}</ceb:logisticsName>
      <ceb:copNo>${this.form.copNo}</ceb:copNo>
      <ceb:assureCode>${this.form.assureCode}</ceb:assureCode>
      <ceb:emsNo>${this.form.emsNo}</ceb:emsNo>
      <ceb:ieFlag>${this.form.ieFlag}</ceb:ieFlag>
      <ceb:declTime>${this.form.declTime}</ceb:declTime>
      <ceb:customsCode>${this.form.customsCode}</ceb:customsCode>
      <ceb:portCode>${this.form.portCode}</ceb:portCode>
      <ceb:ieDate>${this.form.ieDate}</ceb:ieDate>
      <ceb:buyerIdType>${this.form.buyerIdType}</ceb:buyerIdType>
      <ceb:buyerIdNumber>${this.form.buyerIdNumber}</ceb:buyerIdNumber>
      <ceb:buyerName>${this.form.buyerName}</ceb:buyerName>
      <ceb:buyerTelephone>${this.form.buyerTelephone}</ceb:buyerTelephone>
      <ceb:consigneeAddress>${this.form.consigneeAddress}</ceb:consigneeAddress>
      <ceb:agentCode>${this.form.agentCode}</ceb:agentCode>
      <ceb:agentName>${this.form.agentName}</ceb:agentName>
      <ceb:areaCode>${this.form.areaCode}</ceb:areaCode>
      <ceb:areaName>${this.form.areaName}</ceb:areaName>
      <ceb:tradeMode>${this.form.tradeMode}</ceb:tradeMode>
      <ceb:trafMode>${this.form.trafMode}</ceb:trafMode>
      <ceb:country>${this.form.country}</ceb:country>
      <ceb:freight>${this.form.freight}</ceb:freight>
      <ceb:insuredFee>${this.form.insuredFee}</ceb:insuredFee>
      <ceb:currency>${this.form.currency}</ceb:currency>
      <ceb:wrapType>${this.form.wrapType}</ceb:wrapType>
      <ceb:packNo>${this.form.packNo}</ceb:packNo>
      <ceb:grossWeight>${this.form.grossWeight}</ceb:grossWeight>
      <ceb:netWeight>${this.form.netWeight}</ceb:netWeight>
      <ceb:note>${this.form.note}</ceb:note>
    </ceb:InventoryHead>
    <ceb:InventoryList>
      <ceb:gnum>${this.form.gnum}</ceb:gnum>
      <ceb:itemRecordNo>${this.form.itemRecordNo}</ceb:itemRecordNo>
      <ceb:itemNo>${this.form.itemNo}</ceb:itemNo>
      <ceb:itemName>${this.form.itemName}</ceb:itemName>
      <ceb:gcode>${this.form.gcode}</ceb:gcode>
      <ceb:gname>${this.form.gname}</ceb:gname>
      <ceb:gmodel>${this.form.gmodel}</ceb:gmodel>
      <ceb:barCode>${this.form.barCode}</ceb:barCode>
      <ceb:country>${this.form.originCountry}</ceb:country>
      <ceb:tradeCountry>${this.form.tradeCountry}</ceb:tradeCountry>
      <ceb:currency>${this.form.listCurrency}</ceb:currency>
      <ceb:qty>${this.form.qty}</ceb:qty>
      <ceb:unit>${this.form.unit}</ceb:unit>
      <ceb:qty1>${this.form.qty1}</ceb:qty1>
      <ceb:unit1>${this.form.unit1}</ceb:unit1>
      <ceb:price>${price}</ceb:price>
      <ceb:totalPrice>${totalPrice}</ceb:totalPrice>
      <ceb:note>${this.form.note}</ceb:note>
    </ceb:InventoryList>
  </ceb:Inventory>
  <ceb:BaseTransfer>
    <ceb:copCode>${this.form.copCode}</ceb:copCode>
    <ceb:copName>${this.form.copName}</ceb:copName>
    <ceb:dxpMode>${this.form.dxpMode}</ceb:dxpMode>
    <ceb:dxpId>${this.form.dxpId}</ceb:dxpId>
    <ceb:note></ceb:note>
  </ceb:BaseTransfer>
</ceb:CEB621Message>`
          this.dialogVisible = true
        } else {
          this.$message.error('请填写完整所有必填项')
          return false
        }
      })
    },
    copyXml() {
      navigator.clipboard.writeText(this.xmlContent).then(() => {
        this.$message.success('XML已复制到剪贴板')
        this.dialogVisible = false
      }).catch(() => {
        this.$message.error('复制失败，请手动复制')
      })
    },
    downloadXml() {
      const blob = new Blob([this.xmlContent], { type: 'text/xml' })
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = `manifest_${this.form.orderNo}.xml`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(link.href)
      this.$message.success('XML文件已下载')
    }
  }
}
</script>

<style>
/* 全局样式 */
.manifest-xml-drawer {
  overflow: hidden;
}
.drawer-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.drawer-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}
.drawer-footer {
  padding: 20px;
  background: #fff;
  text-align: right;
  border-top: 1px solid #e8e8e8;
}
.xml-content {
  margin: 20px 0;
}
.copy-btn {
  margin-top: 10px;
}
.el-divider {
  margin: 24px 0;
}

/* 表单项样式 */
.manifest-xml-drawer .el-form-item {
  display: flex;
  flex-direction: column;
  margin-bottom: 22px;
}

.manifest-xml-drawer .el-form-item__label {
  display: block !important;
  float: none !important;
  text-align: left !important;
  padding: 0 0 8px !important;
  line-height: 1.5 !important;
  width: 100% !important;
}

.manifest-xml-drawer .el-form-item__content {
  margin-left: 0 !important;
  width: 100% !important;
}

.manifest-xml-drawer .el-select {
  width: 100%;
}
</style>
